package com.roads.plan.controller;

import com.roads.common.constant.Constants;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.plan.domain.PlanProfileBoq;
import com.roads.plan.domain.gantt.PlanProfileGanttTask;
import com.roads.plan.service.IPlanProfileBoqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 形象进度甘特图Controller
 *
 * @author nhp
 * @date 2024-03-08
 */
@RestController
@RequestMapping("/plan/profile/gantt")
public class PlanProfileGanttController  extends BaseController {

    @Autowired
    private IPlanProfileBoqService planProfileBoqService;

    /**
     * 获取形象进度甘特图数据
     *
     * @param institutionCode 标段编号
     * @return 结果
     */
    @PostMapping("/getProfileScheduleGanttData")
    public AjaxResult getProfileScheduleGanttData(String institutionCode) {
        AjaxResult result = new AjaxResult();
        // 查询标段形象清单
        PlanProfileBoq search = new PlanProfileBoq();
        search.setInstitutionCode(institutionCode);
        List<PlanProfileBoq> boqList = planProfileBoqService.selectModelList(search);
        Map<String, PlanProfileBoq> boqMap = new HashMap<>();
        for (PlanProfileBoq boq : boqList) {
            boqMap.put(boq.getBoqCode(), boq);
        }
        List<PlanProfileGanttTask> tasks = new ArrayList<>();
        for (PlanProfileBoq boq : boqList) {
            PlanProfileGanttTask task = new PlanProfileGanttTask();
            task.setId(boq.getId());
            task.setText(boq.getBoqName());
            if (Constants.NO.equals(boq.getLeafNode())) {
                task.setType("milestone");
                task.setOpen(true);
            } else {
                PlanProfileBoq parent = boqMap.get(boq.getParentCode());
                task.setParent(parent.getId());
                task.setStartDate(boq.getStartDate());
                task.setEndDate(boq.getEndDate());
                // 计算完成比例
                BigDecimal total = boq.getTotal() == null ? BigDecimal.ZERO : boq.getTotal();
                BigDecimal alreadyTotal = boq.getRemainderTotal() == null ? BigDecimal.ZERO : boq.getAlreadyTotal();
                if (total.compareTo(BigDecimal.ZERO) == 0) {
                    task.setProgress(BigDecimal.ZERO);
                } else {
                    BigDecimal progress = alreadyTotal.divide(total, 1, BigDecimal.ROUND_HALF_UP);
                    task.setProgress(progress);
                }
            }
            tasks.add(task);
        }
        result.put("data", tasks);
        return result;
    }

}
